package com.pxmeta.dynamic.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.dynamic.entity.TopicUserFollow;
import com.pxmeta.dynamic.mapper.TopicUserFollowMapper;
import com.pxmeta.dynamic.service.ITopicUserFollowService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wcl
 * @since 2022-07-21
 */
@Service
public class TopicUserFollowServiceImpl extends ServiceImpl<TopicUserFollowMapper, TopicUserFollow> implements ITopicUserFollowService {

    @Override
    public void follow(Long userId, Long topicId, Long circleId) {
        boolean follow = isFollow(userId, topicId);
        if (follow){
            throw new ServiceException("不要重复关注！");
        }
        TopicUserFollow userFollow = new TopicUserFollow();
        userFollow.setUserId(userId);
        userFollow.setTopicId(topicId);
        userFollow.setCircleId(circleId);
        this.save(userFollow);
    }

    @Override
    public void unfollow(Long userId, Long topicId) {
        boolean follow = isFollow(userId, topicId);
        if (!follow){
            throw new ServiceException("您还没有关注！");
        }
        LambdaQueryWrapper<TopicUserFollow> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TopicUserFollow::getUserId,userId)
                .eq(TopicUserFollow::getTopicId, topicId);
        this.remove(wrapper);
    }

    @Override
    public List<Long> getFollowTopicIds(Long userId, List<Long> topicIds) {
        if (CollectionUtil.isEmpty(topicIds)){
            return topicIds;
        }
        LambdaQueryWrapper<TopicUserFollow> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TopicUserFollow::getUserId, userId)
                .in(TopicUserFollow::getTopicId, topicIds);
        return this.list(wrapper).stream().map(TopicUserFollow::getTopicId).collect(Collectors.toList());
    }

    @Override
    public boolean isFollow(Long userId, Long topicId){
        LambdaQueryWrapper<TopicUserFollow> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TopicUserFollow::getUserId, userId)
                .eq(TopicUserFollow::getTopicId, topicId);
        TopicUserFollow follow = this.getOne(wrapper);
        return follow != null;
    }
}
